package com.example.jsoup.util;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import cn.hutool.core.util.RandomUtil;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 代理工具类
 * @Date  2021/7/25 15:04
 * @Author YuLe
 **/
@Service
public class ProxyUtil {

    //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ProxyHost, ProxyPort));
    private List<String> proxyList=new ArrayList<>();

    //user-agent
    private List<String> agentList=new ArrayList<>();

    {
        System.out.println("初始化字典开始");
        Resource resource = new ClassPathResource("static/freeProxyAddress.txt");
        BufferedReader bReader = null;
        bReader = new BufferedReader(new InputStreamReader(resource.getStream()));
        StringBuffer sb = new StringBuffer();
        String s = "";
        while (true) {
            try {
                if ((s = bReader.readLine()) == null) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            proxyList.add(s);
        }

        resource = new ClassPathResource("static/agent.txt");
        bReader = new BufferedReader(new InputStreamReader(resource.getStream()));
        while (true) {
            try {
                if ((s = bReader.readLine()) == null) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            agentList.add(s);
        }
        System.out.println("初始化字典完毕" + proxyList.size() + "=" + agentList.size());
    }

    /**
     * 随机获取一条代理
     * @return
     */
    public String getproxy(){
        int proSize = proxyList.size();
        return proxyList.get(RandomUtil.randomInt(0,proSize));
    }

    /**
     * 随机获取一条浏览器信息
     * @return
     */
    public String getAgent(){
        int size = agentList.size();
        int index = RandomUtil.randomInt(0,size);
        return agentList.get(index);
    }


}
